<!--
 * @Author       : 郭庆红
 * @Date         : 2025-03-04 15:14:29
 * @LastEditors  : 郭庆红
 * @LastEditTime : 2025-03-21 09:56:35
 * @FilePath     : e:\project\zhlx-autoform-ui\src\components\ZHLX-Components\ZHLX-processSelect\components\select-process-dialog.vue
 * @Description  : 
 * Copyright 2025 OBKoro1, All Rights Reserved. 
 * 2025-03-04 15:14:29
-->
<template>
  <el-dialog
    title="选择流程"
    v-model="visible"
    width="70%"
    append-to-body
    @close="closeDialog"
  >
    <el-form class="process-form" :inline="true" size="small">
      <el-form-item label="流程名称">
        <el-input v-model="form.exampleTitle"></el-input>
      </el-form-item>
      <el-form-item label="创建人">
        <ZHLXCommonSelect
          v-model="form.draftUserId"
          clearable
          :authorityList="['department']"
          choosePerson="person"
        />
      </el-form-item>
      <el-form-item label="创建人部门">
        <ZHLXCommonSelect
          v-model="form.draftDeptId"
          clearable
          :authorityList="['department']"
          choosePerson="organize"
        />
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker
          v-model="form.createTime"
          type="date"
          placeholder="创建日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="流程分类">
        <el-tree-select
          v-model="form.businessCode"
          :data="computedDictList"
          :expand-on-click-node="false"
          style="width: 100%"
          virtual-scroll
          check-strictly
          :render-after-expand="false"
          :props="{ value: 'code', label: 'name', children: 'children' }"
          @node-click="nodeClick"
          placeholder="流程分类"
        >
          <template #default="{ node }">
            <span :title="node.label">{{ node.label }}</span>
          </template>
        </el-tree-select>
      </el-form-item>

      <el-form-item label="模板选择">
        <el-select
          clearable
          v-model="form.template"
          value-key="templateId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in templateList"
            :key="item.templateId"
            :value="item"
            :label="item.templateName"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="流程状态">
        <el-select clearable v-model="form.exampleStatus" placeholder="请选择">
          <el-option
            v-for="item in computedExampleStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="接收时间">
        <el-select clearable v-model="form.acceptTime" placeholder="请选择">
          <el-option
            v-for="item in computedAcceptTimeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      class="process-table"
      ref="multipleTable"
      border
      stripe
      v-loading="loading"
      row-key="exampleId"
      @selection-change="handleSelectionChange"
      :data="tableData"
    >
      <el-table-column
        :reserve-selection="true"
        fixed
        type="selection"
        width="55"
      />
      <el-table-column prop="exampleTitle" label="流程名称" />
      <el-table-column prop="draftUserName" label="发起人" />
      <el-table-column prop="createTime" label="办理时间" />
      <el-table-column prop="exampleStatus" label="流程状态">
        <template #default="scope">
          {{ getExampleStatusOptions(scope.row.exampleStatus) }}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :page-size="pagination.size"
      :total="pagination.total"
      v-model="pagination.currentPage"
      @current-change="handleCurrentChange"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted, nextTick } from "vue";
import { flowSelectComponent, getTemplateFlowList } from "@/api/workflow/index";
import ZHLXCommonSelect from "@/components/ZHLX-Components/common/commonSelect/index2.vue"; // 选人组件
import { getDicts, postSysTreeDictItemList } from "@/api/dict/dict";
// import type { ElTable } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  multipleSelection: {
    type: Array,
    default: () => [],
  },
  options: {
    type: Object,
    default: () => ({}),
  },
});

const cachePropsMultipleSelection = ref([]);
//
const multipleTable = ref();

const emit = defineEmits([
  "update:modelValue",
  "search",
  "reset",
  "confirm",
  "cancel",
]);

const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});

const acceptTimeOptions = [
  {
    label: "最近6个月",
    value: "6MONTHS",
  },
  {
    label: "最近12个月",
    value: "LAST_12_MONTHS",
  },
  {
    label: "最近18个月",
    value: "18MONTHS",
  },
  {
    label: "全部",
    value: "ALL",
  },
];

const createFormOptions = () => {
  return {
    exampleTitle: "",
    businessCode: "",
    draftUserId: "",
    draftDeptId: "",
    createTime: "",
    exampleStatus: "",
    acceptTime: "",
    template: {},
  };
};
const form: any = ref(createFormOptions());
const tableData = ref([]);
const loading = ref(false);
const pagination = ref({
  currentPage: 1,
  total: 0,
  size: 20,
});

const getList = async () => {
  loading.value = true;
  const { templateId, mainVersionId } = form.value.template;
  const businessCode = [businessTypeCode.value, form.value.businessCode];
  const params = {
    ...form.value,
    businessCode: businessCode.filter((item) => item),
    templateId: +templateId,
    mainVersionId: +mainVersionId,
    current: pagination.value.currentPage,
    size: pagination.value.size,
  };
  delete params.template;
  const res = await flowSelectComponent(params).catch((res) => {
    loading.value = false;
    console.log("流程列表接口调用失败", res, "----");
  });
  if (res && res.code === 0) {
    const { total, records, size } = res.data || {};
    tableData.value = records;
    pagination.value.total = total;
    pagination.value.size = size || 20;
    // 获取到数据后，判断是否需要回填
    nextTick(() => {
      checkBoxIsSelect();
    });
  }
  loading.value = false;
};
const closeDialog = () => {
  visible.value = false;
  emit("cancel");
};

const checkBoxIsSelect = () => {
  // 回填逻辑 从table中找到该对象 去进行回填
  const selectionMap = new Map(
    cachePropsMultipleSelection.value.map((v) => [v.exampleId, v])
  );
  tableData.value.forEach((item) => {
    if (selectionMap.has(item.exampleId)) {
      multipleTable.value?.toggleRowSelection(item, true);
      selectionMap.delete(item.exampleId);
    }
  });
  cachePropsMultipleSelection.value = Array.from(selectionMap.values());
};

/**
 * 初始化 缓存之前选中的 并请求数据进行回填操作
 */
const init = async () => {
  (props.options.seachConfig || []).map((item) => {
    if (item.value) {
      form.value[item.key] = item.value;
    }
  });
  cachePropsMultipleSelection.value = props.multipleSelection;
  if (form.value.businessCode) {
    const code = form.value.businessCode;
    const findItem = props.options.seachConfig?.find(((item) => item.key === "businessCode"));
    let target = null;
    const options = findItem?.props.options;
    const findTarget = (nodes) => {
      for (let i of nodes) {
          if (i.code === code) {
              target = i;
              return; // 找到目标后退出循环
          }
          if (i.children && i.children.length > 0) {
              findTarget(i.children);
              return // 递归查找子节点
          }
      }
    }
    findTarget(options);
    businessTypeCode.value = target.treeDictCode || target.code;
    if (target.code == "document") {
      businessTypeCode.value = "";
    }
    getTemplateList(form.value.templateId);
  }
  await getList();
};

const search = () => {
  getList();
};

/**
 * 分页改变时候 去更新分页数据
 * @param val 当前页
 */
const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  getList();
};

/**
 * 重置方法
 */
const reset = () => {
  form.value = createFormOptions();
  businessTypeCode.value = "";
  pagination.value.currentPage = 1;
  pagination.value.size = 20;
};

const confirm = () => {
  const list = [
    ...cachePropsMultipleSelection.value,
    ...multipleSelection.value,
  ].map((item) => {
    return {
      exampleId: item.exampleId,
      exampleTitle: item.exampleTitle,
      templateId: item.templateId,
      businessCode: item.businessCode,
      exampleStatus: item.exampleStatus,
    };
  });
  emit("confirm", list);
};

// 多选数据
const multipleSelection = ref([]);

// 多选方法
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const exampleStatusOptions = ref([]);

/**
 * 初始化流程状态字典
 */
const initDicts = async () => {
  const res = await getDicts("flow_task_status");
  exampleStatusOptions.value = res.data;
};

// 格式化表格中流程状态的文字
const getExampleStatusOptions = (status: string) => {
  return computed(
    () =>
      exampleStatusOptions.value.find((item) => item.value === status)?.label ||
      ""
  );
};

const dictList = ref([]);

/**
 * 根据字典查询字典项集合
 * @param dictCodeArr 字典类型数组
 * @returns
 */
async function useTreeDictFetch(dictCodeArr: string[]) {
  try {
    const res = await postSysTreeDictItemList(dictCodeArr);
    return res.data || [];
  } catch (error) {
    return [];
  }
}

onMounted(async () => {
  // 流程分类字典
  await initDicts();
  dictList.value = await useTreeDictFetch(["document", "businessTypeDict"]);
  (props.options.seachConfig || []).forEach((item) => {
    if (item.key === "exampleStatus") {
      item.props.options = exampleStatusOptions.value;
    }
    if (item.key === "businessCode") {
      item.props.options = dictList.value;
    }
    if (item.key === "acceptTime") {
      item.props.options = acceptTimeOptions;
    }
  });
});

/**
 * 流程分类树
 */
const templateList = ref([]);
const businessTypeCode = ref("");
/**
 * 节点点击时 去格式化模板列表
 * @param node 当前节点
 */
const nodeClick = (node: any) => {
  businessTypeCode.value = node.treeDictCode || node.code;
  if (node.code == "document") {
    businessTypeCode.value = "";
  }
  form.value.businessCode = node.code;
  templateList.value = [];
  form.value.template = "";
  getTemplateList();
};
/**
 * 根据流程分类获取模板列表
 */
const getTemplateList = async (id?: string) => {
  const params = {
    businessCode: form.value.businessCode,
    isIncludeSub: 1,
    businessTypeCode: businessTypeCode.value,
  };
  const res = await getTemplateFlowList(params).catch(() => {
    console.log("流程数据获取失败~~~~~");
  });
  if (res.code === 0) {
    templateList.value = res.data || [];
    if (id) {
      form.value.template = templateList.value.find((item) => item.templateId == id);
    }
  }
};

// 格式化options
const computedExampleStatusOptions = computed(() => {
  const findItem =  (props.options.seachConfig || []).find((item) => {
    return item.key === 'exampleStatus'
  })
  return exampleStatusOptions.value.filter((item) => {
    return !findItem.options.includes(item.value)
  })
})
const computedAcceptTimeOptions = computed(() => {
  const findItem =  (props.options.seachConfig || []).find((item) => {
    return item.key === 'acceptTime'
  })
  return acceptTimeOptions.filter((item) => {
    return !findItem.options.includes(item.value)
  })
})

const computedDictList = computed(() => {
  // 获取配置项
  const dictConfig = (props.options.seachConfig || []).find(
    item => item.key === 'businessCode'
  )?.options || [];

  // 生成需要排除的code集合（包含父级及其所有子级）
  const exclusionSet = new Set();
  
  // 递归收集父级的所有子级code
  const collectChildrenCodes = (nodes) => {
    nodes.forEach(node => {
      exclusionSet.add(node.code);
      if (node.children?.length) {
        collectChildrenCodes(node.children);
      }
    });
  };

  // 遍历配置项中的每个code，找到对应的节点并收集其子级
  dictConfig.forEach(targetCode => {
    const findNode = (nodes) => {
      for (const node of nodes) {
        if (node.code === targetCode) {
          collectChildrenCodes([node]);
          return true;
        }
        if (node.children?.length && findNode(node.children)) {
          return true;
        }
      }
      return false;
    };
    
    findNode(dictList.value);
  });

  // 过滤原始数据
  const filterTree = (nodes) => 
    nodes
      .filter(node => !exclusionSet.has(node.code))
      .map(node => ({
        ...node,
        children: node.children ? filterTree(node.children) : []
      }))
      .filter(node => node.children?.length || !exclusionSet.has(node.code));
  return filterTree(dictList.value);
});


defineExpose({
  init,
});
</script>

<style lang="scss" scoped>
.pagination {
  padding-top: 20px;
  justify-content: center;
}
.process-form {
  :deep(.el-form-item__content) {
    min-width: 200px !important;
  }
}
.process-table {
  margin-top: 10px;
}
</style>
